package com.xhu.rjsx2.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.xhu.rjsx2.enums.AppHttpCodeEnum;
import com.xhu.rjsx2.pojo.ResponseResult;
import com.xhu.rjsx2.pojo.User;
import com.xhu.rjsx2.pojo.dto.LoginUserDTO;
import com.xhu.rjsx2.service.UserService;
import com.xhu.rjsx2.util.BeanCopyUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.omg.CORBA.SystemException;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author xhu-zfx
 * @email <756867768@qq.com>
 * @date 2023/5/9 20:28
 * @description 用于登录注册接口
 */
@Api(tags = "登录相关接口", description = "Login Controller")
@RestController
@RequestMapping("/user")
public class LoginController {

    @Resource
    private UserService userService;


    @PostMapping("/login")
    @ApiOperation(value = "登录接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名"),
            @ApiImplicitParam(name = "password", value = "密码")
    })
    public ResponseResult login(@RequestBody LoginUserDTO loginUserDTO){
        // 后端校验
        if (StrUtil.isBlankIfStr(loginUserDTO.getUsername()))
            return ResponseResult.errorResult(AppHttpCodeEnum.REQUIRE_USERNAME);
        return userService.login(loginUserDTO.getUsername(),loginUserDTO.getPassword(),loginUserDTO.getRole());
    }

    @PostMapping("/register")
    public ResponseResult register(@RequestBody User user){
        if (StrUtil.isBlankIfStr(user.getUsername()))
            return ResponseResult.errorResult(AppHttpCodeEnum.REQUIRE_USERNAME);
//        User user = BeanCopyUtils.copyBeanSingle(loginUserDTO, User.class);
        user.setId(null);
        // 使用spring的DigestUtils进行MD5加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        String now = DateUtil.now();
        user.setLastLoginTime(DateUtil.parse(now));
        user.setRole("管理员");
        user.setHeader("http://rued9prih.hn-bkt.clouddn.com/FoOp9CxNmERSrimeQjp8MgFxagw-");
        boolean saveSuccess = userService.save(user);
        return saveSuccess ? ResponseResult.okResult() : ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
    }


}
